const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    doctor: {
      doctorName: '',
      doctorTitle: '', //职称
      departmentName: '', //科室名称
      departmentId: '', // 科室Id
      doctorDetail: '', //医生介绍
      settingNum: '', //预约次数
    },
    doctorStatus: true,
    userPhoto: '', //用户上传的头像
    fileList: [], //需要上传的图片
    showTime: false, //时间弹窗
    showSheet: false, //选择器弹窗
    currentDate: '',
    currentDate: new Date().getTime(),
    minDate: new Date('1990-02-01').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },

    selectStr: '', //选择弹窗绑定的属性
    actions: [],

    departmentList: [], //科室
    weekList: [{
        weekText: '周一',
        weekNum: '1',
        isSelect: false
      },
      {
        weekText: '周二',
        weekNum: '2',
        isSelect: true
      },
      {
        weekText: '周三',
        weekNum: '3',
        isSelect: false
      },
      {
        weekText: '周四',
        weekNum: '4',
        isSelect: false
      },
      {
        weekText: '周五',
        weekNum: '5',
        isSelect: false
      },
      {
        weekText: '周六',
        weekNum: '6',
        isSelect: false
      },
      {
        weekText: '周日',
        weekNum: '7',
        isSelect: false
      },
    ],
    timeList: [{ //可预约时间段
        time: '08:00-08:30',
        isSelect: false,
        num: 0
      },
      {
        time: '08:30-09:00',
        isSelect: false,
        num: 0
      },
      {
        time: '09:00-09:30',
        isSelect: false,
        num: 0
      },
      {
        time: '09:30-10:00',
        isSelect: false,
        num: 0
      },
      {
        time: '10:00-10:30',
        isSelect: false,
        num: 0
      },
      {
        time: '10:30-11:00',
        isSelect: false,
        num: 0
      },
      {
        time: '11:00-11:30',
        isSelect: false,
        num: 0
      },
      {
        time: '13:30-14:00',
        isSelect: false,
        num: 0
      },
      {
        time: '14:00-14:30',
        isSelect: false,
        num: 0
      },
      {
        time: '14:30-15:00',
        isSelect: false,
        num: 0
      },
      {
        time: '15:00-15:30',
        isSelect: false,
        num: 0
      },
      {
        time: '15:30-16:00',
        isSelect: false,
        num: 0
      }
    ],
    showWeekTime: false, //选择出诊日期
    showSelectTime: false, //选择出诊时间段
    isSelectWeek: false, //是否选择出诊日期
    isSelectTime: false, //是否选择时间段

    isFirst: '',
    tipShow: '',
    codeNum: ''
  },

  selectWeekItem(e) {
    var index = e.currentTarget.dataset.index,
      weekList = this.data.weekList;

    weekList[index].isSelect = !weekList[index].isSelect
    this.setData({
      weekList
    })
  },
  selectTimeItem(e) {
    var index = e.currentTarget.dataset.index,
      timeList = this.data.timeList;

    timeList[index].isSelect = !timeList[index].isSelect
    this.setData({
      timeList
    })
  },

  onSelfChange(e) {
    this.setData({
      doctorStatus: e.doctorDetail
    })

    console.log(this.data);
  },

  selectWeek() {
    this.setData({
      showWeekTime: true
    })
  },
  selectTime() {
    this.setData({
      showSelectTime: true
    })
  },

  onWeekClose() {
    var list = this.data.weekList,
      flag = list.some(item => {
        return item.isSelect
      });
    this.setData({
      showWeekTime: false,
      isSelectWeek: flag
    })
  },

  onTimeClose() {
    var list = this.data.timeList,
      flag = list.some(item => {
        return item.isSelect
      });
    this.setData({
      showSelectTime: false,
      isSelectTime: flag
    })
  },

  // 上传头像
  upHandle() {
    var that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success(res) {
        console.log(res.tempFiles)
        that.setData({
          userPhoto: res.tempFiles[0],
          fileList: res.tempFiles,
        })
        console.log(that.data.userPhoto);
      }
    })
  },

  // 保存
  saveHandle() {
    var doctor = this.data.doctor,
      weekNum = '',
      timeSlot = '',
      timesList = [];
    console.log(doctor);

    if (this.data.fileList.length == 0) {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      })
      return
    }
    if (doctor.doctorName == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
    if (doctor.departmentName == '') {
      wx.showToast({
        title: '请选择您的科室',
        icon: 'none'
      })
      return
    }
    if (this.data.isSelectWeek && this.data.isSelectTime && doctor.settingNum == '') {
      wx.showToast({
        title: '请输入号段预约次数',
        icon: 'none'
      })
      return
    }

    this.data.weekList.forEach(ele => {
      if (ele.isSelect) {
        weekNum += ele.weekNum + ','
      }
    })
    this.data.timeList.forEach(ele => {
      if (ele.isSelect) {
        timeSlot += ele.time + ','
      }
    })

    console.log(weekNum);
    console.log(timeSlot);
    console.log(doctor);

    var url = app.globalData.url + "doctor/updateDoctor",
      that = this;
    wx.showLoading({
      title: '',
    })

    wx.uploadFile({
      filePath: that.data.fileList[0].tempFilePath,
      name: 'file',
      url: url,
      formData: {
        doctorId: doctor.doctorId,
        doctorName: doctor.doctorName,
        doctorTitle: doctor.doctorTitle,
        departmentId: doctor.departmentId,
        doctorStatus: that.data.doctorStatus ? 1 : 0,
        doctorDetail: doctor.doctorDetail,
        inuserId: app.globalData.userId
      },
      success(res) {
        var res = JSON.parse(res.data)
        console.log(res);
        if (res.flag) {
          console.log(res);
          wx.hideLoading()
          app.globalData.doctor = res.data.doctor
          wx.setStorageSync('doctor', JSON.stringify(res.data.doctor))
          wx.setStorageSync('user', JSON.stringify(app.globalData.user))
          wx.showModal({
            title: '提示',
            content: '信息保存成功',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) {
                wx.navigateBack()
              }


            }
          })
        }
      }
    })
    console.log(doctor);
  },
  // 输入框编辑
  inputHandle(e) {
    var str = e.currentTarget.dataset.flag
    var val = e.detail.value
    this.setData({
      [str]: val
    })
  },

  // 选择出生日期
  showTimeHandle() {
    this.setData({
      showTime: true
    })
  },
  // 关闭时间选择
  onClose() {
    this.setData({
      showTime: false
    })
  },

  // 确认日期
  confirmTime(event) {
    console.log(event);
    var date = new Date(event.detail)
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var strDate = Y + M + D;
    console.log(strDate);
    var str = 'doctor.birthDate'
    this.setData({
      [str]: strDate,
      showTime: false
    });
  },
  // 显示选择弹窗
  showSelect(e) {
    console.log(e);
    var str = e.currentTarget.dataset.flag
    if (str == 'doctor.departmentName') {
      this.setData({
        actions: this.data.departmentList
      })
      console.log(this.data.actions);
    }
    this.setData({
      selectStr: str,
      showSheet: true
    })

  },

  // 选择弹窗  确认
  onSelect(e) {
    console.log(e);
    if (this.data.selectStr == 'doctor.departmentName') {
      var str = 'doctor.departmentId'
    }
    this.setData({
      [this.data.selectStr]: e.detail.name,
      [str]: e.detail.id,
      showSheet: false
    })
  },





  getDepartmentList() {
    var url = app.globalData.url + "doctor/listDepartment",
      that = this,
      doctor = this.data.doctor,
      departmentList = [];
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {}, res => {
        console.log(res);
        if (res.flag) {
          wx.hideLoading()
          var datas = res.data

          datas.forEach(ele => {
            if (ele.departmentId == doctor.departmentId) {
              doctor.departmentName = ele.departmentName
            }
            departmentList.push({
              name: ele.departmentName,
              id: ele.departmentId,
            })
          })

          console.log(departmentList);

          that.setData({
            departmentList,
            doctor
          })
        }
      },
      err => {
        console.log(err);
      })
  },


  tipConfirm(e) {
    if (this.data.codeNum == '') {
      wx.showToast({
        title: '请输入兑换码',
        icon: 'none'
      })
      return
    }

    console.log(this.data.codeNum);

    var url = app.globalData.url + "doctor/updateUserType",
      that = this;
    wx.showLoading({
      title: '',
    })
    app.wxRequest(url, {
        userId: app.globalData.userId,
        code: that.data.codeNum,
        userName: app.globalData.user.userName,
      }, res => {
        console.log(res);
        if (res.flag) {
          wx.hideLoading()
          var datas = res.data

          console.log(datas);
          wx.showToast({
            title: datas.msg,
            icon: 'none'
          })

          if (datas.flag == 'success') {
            app.globalData.user.userType = datas.userType
            app.globalData.userType = datas.userType
            app.globalData.doctor = datas.doctor
            app.globalData.doctorId = datas.doctor.doctorId
            that.setData({
              doctor: datas.doctor
            })
            wx.setStorageSync('doctor', JSON.stringify(datas.doctor))
            console.log(datas.doctor);
            console.log(app.globalData);
            wx.showModal({
              title: '提示',
              content: '您已成功兑换医生身份，请完善您的基本信息',
              showCancel: false,
              complete: (res) => {
                if (res.confirm) {

                }
              }
            })
          }

          that.setData({
            codeNum: ''
          })
        }
      },
      err => {
        console.log(err);
      })




  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    var doctor = app.globalData.doctor || JSON.parse(wx.getStorageSync('doctor')),
      user = app.globalData.user;
    console.log(user);
    console.log(user.userName != null);
    if (user.userName != null) {
      doctor.doctorName = user.userName
    }

    this.setData({
      doctor: app.globalData.doctor || JSON.parse(wx.getStorageSync('doctor')),
      isFirst: app.globalData.isDoctorFirst,
      tipShow: app.globalData.isDoctorFirst
    })

    console.log(this.data);
    this.getDepartmentList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})